<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 

class Currency{
	
	function __construct(){
		$this->ci =& get_instance();

		$this->ci->load->library('session');
		$this->ci->load->database();
		$this->ci->load->model('currency/currency_model');
		
		$query = $this->ci->currency_model->getCurrency();
		foreach($query as $row){
			$this->ci->session->set_userdata(array(
				'currency_id'   => $row->currency_id,
				'code'   		=> $row->code,
				'title'         => $row->title,
				'symbol_left'   => $row->symbol_left,
				'symbol_right'  => $row->symbol_right,
				'value'         => $row->value
			));
		}
		
	}
	
	function setCurrency($currency = '') {
		if($currency == NULL){
			$data['set_currency'] = $this->ci->currency_model->defaultCurrency();
			$this->ci->session->set_userdata('sess_currency',$data['set_currency']);
		}else{
			if (!empty($currency)) {
				$data['set_currency'] = $currency;
				$this->ci->session->set_userdata('sess_currency',$data['set_currency']);
			}else{
				$data['set_currency'] = $this->ci->session->userdata('sess_currency');
			}
		}
    }
	
	function getCurrency(){
			return $this->ci->session->userdata('sess_currency');	
	}
	
	function defaultCurrency(){
			return $this->ci->currency_model->defaultCurrency();
	}
	
	function format($number, $currency = '', $format = TRUE){
		if ($currency) {
      		$symbol_left   = $this->ci->currency_model->getSymbolLeft($currency);
      		$symbol_right  = $this->ci->currency_model->getSymbolRight($currency);
    	} else {
      		$symbol_left   = $this->ci->currency_model->getSymbolLeft($currency);
      		$symbol_right  = $this->ci->currency_model->getSymbolRight($currency);
    	}
		
		$value = '';
		if ($value) {
      		$value = $value;
    	} else {
      		$value = $this->ci->currency_model->getValue($currency);
			foreach($value as $value){
				$value = $value->value;
			}
    	}
		
    	if ($value) {
      		$value = $number * $value;
    	} else {
      		$value = $number;
    	}

    	$string = '';

    	if (($symbol_left) && ($format)) {
      		$string .= $symbol_left;
    	}
		
		$string .= number_format(round($value, 2),2,',','.');
		
		if (($symbol_right) && ($format)) {
      		$string .= $symbol_right;
    	}

    	return $string;	
	}
	
	function Currency($currency){
		if($currency){
			return $this->ci->currency_model->Currency($currency);	
		}
	}
	
	function getId(){
		return $this->ci->session->userdata('currency_id');
	}

} 

?>
